package com.css.zfzx.sjcj.modules.statistics.fxqhHddc200.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.zfzx.sjcj.common.utils.CheckObjFields;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.common.vo.DivisionVo;
import com.css.zfzx.sjcj.modules.pojo.PcStatisticsFillVO;
import com.css.zfzx.sjcj.modules.pojo.QueryVo;
import com.css.zfzx.sjcj.modules.statistics.dao.primary.SuperDao;
import com.css.zfzx.sjcj.modules.statistics.fxEconomicLossLevelMap.repository.entity.FxEconomicLossLevelMapVO;
import com.css.zfzx.sjcj.modules.statistics.fxqhHddc100.repository.entity.FxqhHdc100Entity;
import com.css.zfzx.sjcj.modules.statistics.fxqhHddc100.repository.entity.FxqhHdc100VO;
import com.css.zfzx.sjcj.modules.statistics.fxqhHddc200.repository.entity.FxqhHdc200Entity;
import com.css.zfzx.sjcj.modules.statistics.fxqhHddc200.repository.FxqhHddc200Repository;
import com.css.zfzx.sjcj.modules.statistics.fxqhHddc200.repository.entity.FxqhHdc200VO;
import com.css.zfzx.sjcj.modules.statistics.fxqhHddc200.service.FxqhHddc200Service;
import com.css.zfzx.sjcj.modules.statistics.qhProbabilityEarthquakeDanger.repository.entity.QhProbabilityEarthquakeDangerEntity;
import com.css.zfzx.sjcj.modules.sys.usersInfo.UsersVo;
import com.css.zfzx.sjcj.modules.sys.usersInfo.repository.UsersInfoRepository;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FxqhHddc200ServiceImpl implements FxqhHddc200Service {
    @Autowired
    private FxqhHddc200Repository nativeRepository;
    @Autowired
    private SuperDao superDao;
    @Autowired
    UsersInfoRepository usersInfoRepository;
    List<UsersVo> usersVoList = new ArrayList<>();
    @PostConstruct
    public void init(){
        usersVoList = usersInfoRepository.getAll();
    }
    @Override
    public List<PcStatisticsFillVO> findCreateTime(LocalDateTime createTime) {
        List<PcStatisticsFillVO> entities = nativeRepository.findCreateTime(createTime);
        return entities;
    }

    @Override
    public List<PcStatisticsFillVO> findUpdateTime(LocalDateTime updateTime) {
        List<PcStatisticsFillVO> entities = nativeRepository.findUpdateTime(updateTime);
        return entities;
    }

    @Override
    public List<DivisionVo> count(int identify) {
        return nativeRepository.count(identify);
    }

    @Override
    public JSONObject find(QueryVo queryVo, String userId, int curPage, int pageSize, String sort, String order) {
        if (!PlatformObjectUtils.isEmpty(sort) && sort.length() > 0) {
            sort = CheckObjFields.propertyChange(sort);
        }
        Page<FxqhHdc200VO> vos =nativeRepository.find(queryVo, userId, curPage, pageSize, sort, order);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", getVOs(userId, vos.getContent()));
        jsonObject.put("total", vos.getTotalElements());
        return jsonObject;
    }

    @Override
    public void export(String userId, HttpServletResponse resp) {
        OutputStream out = null;
        try {
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String name = dateStr + "地震灾害防治区划图（活动断层200m避让缓冲区）.xlsx";
            //resp.setContentType("application/octet-stream ");
            resp.setHeader("content-Type", "application/vnd.ms-excel");
            resp.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
            //resp.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
            resp.setHeader("Content-Disposition", "attachment;fileName="
                    + new String(name.getBytes("GB2312"), "ISO8859-1"));
            resp.setCharacterEncoding("UTF-8");

            XSSFWorkbook workbook = new XSSFWorkbook();// 创建一个Excel文件
            // 样式设置
            XSSFCellStyle columnHeadStyle = workbook.createCellStyle();
            columnHeadStyle.setFillPattern(FillPatternType.NO_FILL); // 背景
            columnHeadStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex()); // 背景色AQUA.getIndex()
            columnHeadStyle.setBorderBottom(BorderStyle.THIN); // 下边框
            columnHeadStyle.setBorderLeft(BorderStyle.THIN);// 左边框
            columnHeadStyle.setBorderTop(BorderStyle.THIN);// 上边框
            columnHeadStyle.setBorderRight(BorderStyle.THIN);// 右边框
            columnHeadStyle.setAlignment(HorizontalAlignment.CENTER);//左右居中
            columnHeadStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);// 上下居中
            columnHeadStyle.setWrapText(true);//自动换行

            XSSFSheet sheet = workbook.createSheet("地震灾害防治区划图（活动断层200m避让缓冲区）");
            String[] sheetHeadTitle = new String[]{"省", "市", "区(县)", "断层编号", "断层名称", "是否上报pg库", "上传人", "上传日期"};
            ConvertUtils.register(new DateConverter(null), java.util.Date.class);
            List<FxqhHdc200VO> vOs = getVOs(userId, nativeRepository.findNoPage(userId));
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, sheetHeadTitle.length - 1));
            for (int i = 0; i < vOs.size() + 2; i++) {
                XSSFRow row0 = sheet.createRow(i);
                row0.setHeightInPoints(30);
                String[] values =null;
                if (i>1){
                    values = CheckObjFields.objectChangeArray(vOs.get(i - 2));
                }
                for (int t = 0; t < sheetHeadTitle.length; t++) {
                    XSSFCell cel0_i = row0.createCell(t);
                    if (i == 0 && t == 0) {
                        cel0_i.setCellValue(new XSSFRichTextString("地震灾害防治区划图（活动断层200m避让缓冲区）"));
                    } else if (i == 1) {
                        cel0_i.setCellValue(new XSSFRichTextString(sheetHeadTitle[t]));
                    } else if (i > 1) {
                        if (t==5){
                            if ("1".equals(values[t])){
                                cel0_i.setCellValue(new XSSFRichTextString("已上报"));
                            }else {
                                cel0_i.setCellValue(new XSSFRichTextString("未上报"));
                            }
                        }else {
                            if (StringUtils.isEmpty(values[t])||"null".equals(values[t])){
                                cel0_i.setCellValue(new XSSFRichTextString());
                            }else {
                                cel0_i.setCellValue(new XSSFRichTextString(values[t]));
                            }
                        }
                    }
                    cel0_i.setCellStyle(columnHeadStyle);
                    //sheet.autoSizeColumn((short) t);//宽度自适应
                }
                sheet.setColumnWidth(i, 6000);
            }
            out = resp.getOutputStream();
            workbook.write(out);
            // ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // workbook.write(bos);
            // bos.writeTo(out);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private List<FxqhHdc200VO> getVOs(String userId, List<FxqhHdc200VO> list) {
        for (FxqhHdc200VO vo: list){
            for (UsersVo usersVo:usersVoList){
                String usersId = usersVo.getUsersId();
                if (usersId.equals(vo.getCreateUser())){
                    vo.setCreateUser(usersVo.getUsersName());
                    break;
                }
                if (usersId.equals(userId)){
                    vo.setCreateUser(usersVo.getUsersName());
                    break;
                }
            }
        }
        return list;
    }

    @Override
    public void dataQualityCheck(QueryVo queryVo) {
        List<FxqhHdc200Entity> noPage = nativeRepository.findNoPages(queryVo, null);
        List<FxqhHdc200Entity> updateList=new ArrayList<>();
        try {
            for (FxqhHdc200Entity vo : noPage) {
                //检查字段值不为空
                StringBuilder errorMsg = new StringBuilder();
                Map<String, String> methods = new HashMap<>();
                setCheckFields(methods);
                ServerUtil.checkFieldNull(vo, methods, errorMsg);

                if (StringUtils.isNotEmpty(String.valueOf(errorMsg)) && errorMsg.length() > 0) {
                    vo.setQualityStatus("2");
                    vo.setQualityComment(String.valueOf(errorMsg));
                }else {
                    vo.setQualityStatus("1");
                    vo.setQualityComment(null);
                }
                updateList.add(vo);
            }
            superDao.batchUpdate(updateList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setCheckFields(Map<String, String> methods) {
        methods.put("hdcCode", "断层编号");
        methods.put("hdcName", "断层名称");
    }
}
